package com.sh.weblogspringboot.admin.service.impl;

import com.sh.weblogspringboot.admin.service.AdminUserService;
import com.sh.weblogspringboot.admin.vo.user.FindUserInfoRspVO;
import com.sh.weblogspringboot.admin.vo.user.UpdateAdminUserPasswordReqVO;
import com.sh.weblogspringboot.common.domain.mapper.UserMapper;
import com.sh.weblogspringboot.common.enums.ResponseCodeEnum;
import com.sh.weblogspringboot.common.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author songHai
 * @Classname AdminUserServiceImpl
 * @Description
 * @Date 2025/3/30 14:20
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Response<Integer> updatePassword(UpdateAdminUserPasswordReqVO updateAdminUserPasswordReqVO) {
        String username = updateAdminUserPasswordReqVO.getUsername();
        String password = updateAdminUserPasswordReqVO.getPassword();

        // 加密密码
        String encodePassword = passwordEncoder.encode(password);

        // 更新到数据库
        int count = userMapper.updatePasswordByUsername(username, encodePassword);

        return count == 1 ? Response.success("更新成功") : Response.fail(ResponseCodeEnum.USERNAME_OR_PWD_ERROR);
    }

    @Override
    public Response<FindUserInfoRspVO> findUserInfo() {
        // 获取存储在ThreadLocal中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 拿到用户名
        String username = authentication.getName();

        return Response.success(FindUserInfoRspVO.builder().username(username).build());
    }
}
